﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _4_07_读写文本文件
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //获取文件路径
            OpenFileDialog openFileDialog = new OpenFileDialog();
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                this.textBox1.Text = openFileDialog.FileName;
            }
            else
            {
                return;
            }
            //显示文本内容
            //方案一:FileStream将文件读取为文件流byte[],然后转成转换字符串
            //FileStream fs = new FileStream(this.textBox1.Text,FileMode.Open,FileAccess.Read);
            //int len = (int)fs.Length;//获取文件流中的字节长度
            //byte[] arrByte = new byte[len];//定义字节数组用于保存内容
            //fs.Read(arrByte,0,len);//读入字节数组
            //this.textBox2.Text = Encoding.Default.GetString(arrByte);//将字节数组转换为字符串显示
            //fs.Close();

            //方案二 : FileStream将文件读取为文件流byte[],然后转成转换字符串
            //可以读取部分内容
            //FileStream fs = new FileStream(this.textBox1.Text, FileMode.Open, FileAccess.Read);
            //int length = (int)fs.Length;
            //byte[] arrByte = new byte[length];
            //int index = 0;//数组下标
            //int code = fs.ReadByte();//读取第一个字节 code=-1证明读完了
            //while (code != -1)
            //{
            //    arrByte[index]=Convert.ToByte(code);//读取内容存入数组
            //    code = fs.ReadByte();//继续读字节
            //    index++;
            //}
            //this.textBox2.Text = Encoding.Default.GetString(arrByte);
            //fs.Close();

            //方案三:使用File静态类
            //this.textBox2.Text=File.ReadAllText(this.textBox1.Text, Encoding.UTF8);

            //方案四:使用StreamReader
            FileStream fs = new FileStream(this.textBox1.Text, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.UTF8);
            this.textBox2.Text = sr.ReadToEnd();
            sr.Close();
            fs.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //方案一 : File类静态方法
            //File.WriteAllText(this.textBox1.Text, this.textBox2.Text, Encoding.UTF8);
            //MessageBox.Show("保存成功！");


            //方案二: FileStream + StreamWriter
            FileStream fs = new FileStream(this.textBox1.Text, FileMode.Open, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
            sw.Write(this.textBox2.Text);
            sw.Close();
            fs.Close();
            MessageBox.Show("保存成功！");
        }
    }
}
